<!--
 * @LastEditTime: 2024-09-07 12:37:39
 * @Description: 
 * @Date: 2024-09-07 12:07:58
 * @Author: wangshan
 * @LastEditors: wangshan
-->
<template>
  <el-row>
    <el-col :span="24" style="margin: 24px;">
      <el-form ref="ruleFormRef" :rules="rules" :model="formData" label-width="auto" style="max-width: 80vw">
        <el-form-item label="封面" prop="cover">
          <template v-if="!isEditMode">
            <el-image v-if="formData.coverUri" :src="formData.coverUri" :preview-src-list="[formData.coverUri]"
              fit="cover" style="width: 148px; height: 148px;" class="commodity-image">
              <template #error>
                <div class="image-error">
                  <el-icon>
                    <Picture />
                  </el-icon>
                </div>
              </template>
            </el-image>
            <div v-else class="empty-image">
              <el-icon>
                <Picture />
              </el-icon>
              <span>暂无封面</span>
            </div>
          </template>
          <el-upload v-else v-model:file-list="fileList" :http-request="uploadFile" :limit="maxImgCount"
            :on-change="beforeAvatarUpload" :on-remove="handleRemoveImage" action="#" list-type="picture-card"
            class="commodity-upload">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <input-widget-web v-model="formData.name" label="商品名称" prop="name" :disabled="!isEditMode"
          :rules="[{ required: true, message: '请输入商品名称', trigger: 'blur' }]">
        </input-widget-web>

        <!-- 规格 -->
        <input-widget-web v-model="formData.standard" label="规格" prop="standard" :disabled="!isEditMode" />

        <!-- 替换原商品分类选择器 -->
        <category-select v-model="formData.category" :disabled="!isEditMode" label="商品分类" prop="category"
          :basicUiAction="basicUiAction" @change="handleCategoryChange" />

        <!-- 单位 -->
        <unit-select v-model="formData.unit" :disabled="!isEditMode" label="单位" prop="unit"
          :basicUiAction="basicUiAction" @change="handleUnitChange" />

        <!-- 排序 -->
        <input-widget-web v-model="formData.sorder" label="排序" prop="standard" :numberMode="true" :disabled="!isEditMode" />      

        <!-- 关联的贵金属账户类型 -->
        <self-fund-account-type-select  :disabled="!isEditMode" v-if="supportMetalAccountCommodity" v-model="formData.metalAccountTypeId"
          :fundUiAction="fundUiAction" label="关联贵金属账户类型" @change="handleAccountTypeChange" />

        <!-- 贵金属本身 -->
        <el-form-item  v-if="supportMetalAccountCommodity"  label="贵金属自身" prop="isMetalSelf">
          <el-switch v-model="formData.isMetalSelf" :disabled="!isEditMode || !formData.metalAccountTypeId" active-text="是" inactive-text="否" />
        </el-form-item>

        <!-- 贵金属编码 -->
        <input-widget-web v-if="supportMetalAccountCommodity" v-model="formData.metalCode" label="贵金属价格编码"
          prop="metalCode" :disabled="!isEditMode" placeholder="请输入贵金属价格编码" />



        <!-- 启用状态 -->
        <el-form-item label="启用状态" prop="enabled">
          <el-switch v-model="formData.enabled" :disabled="!isEditMode" active-text="启用" inactive-text="停用" />
        </el-form-item>

        <!-- 备注 -->
        <input-widget-web v-model="formData.remark" label="备注" prop="remark" :disabled="!isEditMode"
          placeholder="请输入备注信息" :remarkMode="true" />

        <!-- 备注 
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" :disabled="!isEditMode" type="textarea" :rows="3" style="width: 400px"
            placeholder="请输入备注信息" />
        </el-form-item>
        -->
        <el-form-item style="margin-left: 70px;">
          <el-button @click="handleSave(ruleFormRef)" v-if="isEditMode" type="primary">保存</el-button>
          <el-button @click=" toggleEditMode(false)" v-if="isEditMode">取消</el-button>
          <el-button @click="removeCommodity()" v-if="!isEditMode" type="danger">删除</el-button>
          <el-button @click="toggleEditMode(true)" v-if="!isEditMode" type="primary">编辑</el-button>
          <el-button @click="closePage()" v-if="!isEditMode">返回</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>



</template>
<script>
import { Picture, View, Edit, Plus, Delete } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { CommodityUiAction } from '../../public/engine/uiAction/commodityUiAction'
import { BasicUiAction } from '../../public/engine/uiAction/basicUiAction'
import { FundUiAction } from '../../public/engine/uiAction/fundUiAction'
import { Commodity } from '../../public/engine/commodity/commodity'
import { SubCommodity } from '../../public/engine/commodity/subCommodity'
import { sendFile } from '@/api/common/common.js'
import { Definition } from '../../public/engine/common/definition'
import InputWidgetWeb from '../../public/views/componentsWeb/InputWidgetWeb.vue'
import CategorySelect from '../../public/views/componentsWeb/CategorySelect.vue'
import UnitSelect from '../../public/views/componentsWeb/UnitSelect.vue'
import { updateOrCreateCommodiy, removeCommodity } from "../../public/network/api"
import { Util } from '../../public/utils/util'
import { ActionResultType, ActionResult } from '../../public/engine/common/actionResult'
import { CsFundDouble } from '../../public/engine/common/csFundDouble'
import { NetworkParser } from '../../public/network/communicationConverter.js';
import { Engine } from '../../public/engine/engine'
import SelfFundAccountTypeSelect from '../../public/views/componentsWeb/SelfFundAccountTypeSelect.vue'
import TabUtil from '@/plugins/tab'
import EventBus from '../../public/engine/ipc/eventBus'




export default {
  name: 'commodity',
  components: {
    Picture,
    View,
    Edit,
    Plus,
    Delete,
    InputWidgetWeb,
    CategorySelect,
    UnitSelect,
    SelfFundAccountTypeSelect
  },

  data() {
    return {
      isEditMode: false,
      commodity: new Commodity(),
      formData: {
      },
      originalCommodity: null,
      commodityUiAction: new CommodityUiAction(),
      basicUiAction: new BasicUiAction(),
      fundUiAction: new FundUiAction(),
      fileList: [],
      // 模拟单位数据 - 实际应从API获取
      unitOptions: [
      ],
      // 返回数据
      retValue: null
    }
  },

  computed: {
    maxImgCount() {
      return Definition.maxCommodityImgCount
    },

    supportMetalAccountCommodity() {
      return Engine.profile.org.isPreciousMetalOrg;
    },
  },

  methods: {

    syncFormData() {
      this.formData = {
        code: this.commodity.code,
        name: this.commodity.name,
        qrCode: this.commodity.qrCode,
        standard: this.commodity.subCommodityList[0]?.standard || '',
        category: this.commodity.category,
        unit: this.commodity.unit,
        enabled: this.commodity.enabled,
        cost: this.commodity.subCommodityList[0]?.cost?.value !== undefined ?
          (this.commodity.subCommodityList[0].cost.value.toString()) :
          null,

        purchasePrice: this.commodity.purchasePrice?.value.toString(),
        retailPrice: this.commodity.retailPrice?.toString(),
        wholesalePrice: this.commodity.wholesalePrice?.value.toString(),
        remark: this.commodity.remark,

        metalAccountTypeId: this.commodity.metalAccountTypeId,
        metalCode: this.commodity.metalCode,
        isMetalSelf: this.commodity.isMetalSelf,
        sorder: this.commodity.sorder
      };

      if (this.commodity.id == null || this.commodity.id == undefined || this.commodity.id == "") {
        this.commodity.cost = null;
        this.commodity.purchasePrice = null;
        this.commodity.retailPrice = null;
        this.commodity.wholesalePrice = null;
      }
    },

    fillWithFormData() {
      this.commodity.code = this.formData.code;
      this.commodity.name = this.formData.name;
      this.commodity.qrCode = this.formData.qrCode;
      this.commodity.category = this.formData.category;
      this.commodity.unit = this.formData.unit;
      this.commodity.enabled = this.formData.enabled;
      this.commodity.cost = new CsFundDouble(this.formData.cost || "0");
      this.commodity.purchasePrice = new CsFundDouble(this.formData.purchasePrice || "0");
      this.commodity.retailPrice = new CsFundDouble(this.formData.retailPrice || "0");
      this.commodity.wholesalePrice = new CsFundDouble(this.formData.wholesalePrice || "0");
      this.commodity.remark = this.formData.remark;
      this.commodity.standard = this.formData.standard;
      this.commodity.metalAccountTypeId = this.formData.metalAccountTypeId;
      this.commodity.metalCode = this.formData.metalCode;
      this.commodity.isMetalSelf = this.formData.isMetalSelf;
      this.commodity.sorder = this.formData.sorder;

      this.commodity.subCommodityList = this.getAndSyncSubCommodities(this.commodity);




      if (this.commodity.subCommodityList.length == 0) {
        ElMessage.error("请至少添加一个子商品!");
        return -1;
      }

      return 0;

    },

    async fetchData(commodityId) {
      try {
        const res = await this.commodityUiAction.getCommodityDetailInfo(commodityId)
        if (res) {
          this.commodity = res;
          this.syncFormData();
          // 初始化文件列表
          if (this.commodity.coverUri) {
            this.fileList = [{
              name: '',
              url: this.commodity.coverUri
            }]
          }

          console.log('----> commodity:', this.commodity);
        }
      } catch (error) {
        ElMessage.error('获取商品详情失败')
        console.error(error)
      }
    },

    // 关闭页面 关闭当前页面
    closePage() {
      // 尝试直接关闭
      try {
        TabUtil.closePage();
        return;
      } catch (e) {
        console.log('直接关闭失败，尝试替代方案');
      }
    },

    handleCategoryChange(val) {
      // 分类选择变化时的处理
      //console.log('Selected category:', val)
      this.formData.category = val;
    },

    handleUnitChange(val) {
      // 单位选择变化时的处理
      //console.log('Selected unit:', val)
      this.formData.unit = val;
    },

    handleAccountTypeChange(val) {
      this.formData.metalAccountTypeId = val.id;
      this.formData.metalCode = val.code;
    },

    // 其他方法保持不变...
    beforeAvatarUpload(file) {
      const isImage = file.type === 'image/png' || file.type === 'image/jpeg' || file.type === 'image/jpg'
      const isLt5M = file.size / 1024 / 1024 < 5

      if (!isImage) {
        ElMessage.error('上传文件格式务必PNG|JPG|JPEG')
        return false
      }
      if (!isLt5M) {
        ElMessage.error('上传文件大小不能超过5MB')
        return false
      }
      return true
    },

    async uploadFile(option) {
      try {
        const file = option.file
        const formData = new FormData()
        formData.append('file', file)

        const res = await sendFile(formData)
        if (res.code === 200) {
          this.formData.coverUri = res.url
          ElMessage.success('上传成功')
        }
      } catch (error) {
        console.error('上传失败:', error)
        ElMessage.error('上传失败')
      }
    },

    handleRemoveImage() {
      this.formData.coverUri = ''
    },

    toggleEditMode(edit) {
      this.isEditMode = edit
      if (!edit) {
        this.syncFormData();
        if (this.formData.coverUri) {
          this.fileList = [{
            name: '',
            url: this.formData.coverUri
          }]
        } else {
          this.fileList = []
        }
      }
    },

    async removeCommodity() {

      if (Util.isEmpty(this.commodity.id)) {
        TabUtil.closePage();
        return;
      }

      try {
        const res = await removeCommodity(this.commodity.id);

        // console.log("handle removeCommodity res:", res)

        let reqResult = NetworkParser.parseNetworkResult(res, null);

        if (reqResult.resErr != null) {
          console.error('删除商品失败', reqResult.resErr);
          ElMessage.error("删除商品失败:" + reqResult.resErr);
          return;
        }
        else if (reqResult.data != null) {
          ElMessage.success('删除商品成功');
          this.retValue = new ActionResult({ type: ActionResultType.Del });
          //uni.$emit('commodityUpdated', this.retValue.toCopyJson())
          //uni.navigateBack();              
          setTimeout(() => {
            console.log("Closing page after deletion");
            TabUtil.closePage();
          }, 1000); // 1000ms = 1 second
        }

      } catch (error) {
        console.error('删除商品失败', error);
        ElMessage.error("删除商品失败:" + error);
      }
    },


    handleEdit() {
      this.isEditMode = true
    },

    /// 生成规格子商品 返回类型：List<SubCommodity>
    getAndSyncSubCommodities(commodity) {
      if (this.commodity.multiStandard || this.commodity.subCommodityList.length > 1) {
        // 同步使能状态，如果commodity 使能为false, 下面子商品全部使能为 false
        if (!this.commodity.enabled) {
          for (var item in this.commodity.subCommodityList) {
            item.enabled = false;
          }
        }
        return this.commodity.subCommodityList;
      } else {
        let standard = this.commodity.standard;

        if (this.commodity.subCommodityList.length == 0) {
          let subCommodity = new SubCommodity({ standard: standard });
          subCommodity.syncCommodityInfo(commodity);
          return [subCommodity];
        } else {
          this.commodity.subCommodityList[0].standard = standard;
          this.commodity.subCommodityList[0].syncCommodityInfo(commodity);
          return this.commodity.subCommodityList;
        }
      }
    },

    async handleSave() {
      try {
        // First validate the form
        await this.$refs.ruleFormRef.validate();

        if (this.fillWithFormData() != 0) {
          return;
        }
        // 提交数据
        const res = await updateOrCreateCommodiy(this.commodity);
        // 解析数据，利用 NetworkParser 解析分页数据
        const reqResult = NetworkParser.parseNetworkResult(res, null);

        if (reqResult.resErr != null) {
          console.error('提交商品数据失败', reqResult.resErr);
          ElMessage.error("提交商品数据失败:" + reqResult.resErr);
          return;
        }
        else if (reqResult.data != null) {
          let type = ActionResultType.None;
          if (Util.isEmpty(this.commodity.id)) {
            type = ActionResultType.New;
          } else {
            type = ActionResultType.UpdateCommon;
          }

          if (Util.isEmpty(this.commodity.id)) {
            // 更新id, 刷新页面
            this.commodity.id = Util.jsonToString(reqResult.data);
            // 通知上级页面更新
            this.retValue = new ActionResult({ type: type, param: this.commodity.toCopyJson() });
            ElMessage.success("创建成功!");
            this.isEditMode = false;
            this.fetchData(this.commodity.id); // 刷新数据 
            // uni.$emit('commodityUpdated', this.retValue.toCopyJson())                    
          } else {
            ElMessage.success("更新成功!");
            this.isEditMode = false;
            this.fetchData(this.commodity.id); // 刷新数据                    
            this.retValue = new ActionResult({ type: type, param: null });  // 最后返回时候设置param
          }
        }
      } catch (error) {
        ElMessage.error('保存商品失败')
        console.error(error)
      }
    },
  },
  mounted() {
    this.retValue = null;
    const commodityId = this.$route.params.id || this.$route.query.id;
    this.syncFormData();
    if (commodityId) {
      this.fetchData(commodityId)
    } else {
      // 新建
      this.isEditMode = true
    }
  },



  // 卸载页面
  beforeUnmount() {
    // console.log('---> commodityDetailPage beforeUnmount');
    if (this.retValue) {
      EventBus.emit('commodityUpdated', this.retValue.toCopyJson());
      this.retValue = null;
    }
  },

  // 页面被隐藏时触发
  deactivated() {
    // console.log('---> commodityDetailPage deactivated');
    if (this.retValue) {
      EventBus.emit('commodityUpdated', this.retValue.toCopyJson())
      this.retValue = null;
    }
  },


}
</script>

<style>
.commodity-image {
  border-radius: 4px;
  border: 1px solid #dcdfe6;
}

.empty-image {
  width: 148px;
  height: 148px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
  color: #8c939d;
}

.image-error {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f7fa;
  color: #c0c4cc;
}
</style>